package com.ruoyi.system.service.impl;

import java.util.List;

import com.ruoyi.system.domain.Contract;
import com.ruoyi.system.mapper.ContractMapper;
import com.ruoyi.system.util.DoubleUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.ConstractRecordMapper;
import com.ruoyi.system.domain.ConstractRecord;
import com.ruoyi.system.service.IConstractRecordService;
import com.ruoyi.common.core.text.Convert;

/**
 * 到款信息Service业务层处理
 *
 * @author ruoyi
 * @date 2022-04-04
 */
@Service
public class ConstractRecordServiceImpl implements IConstractRecordService {
    @Autowired
    private ConstractRecordMapper constractRecordMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询到款信息
     *
     * @param id 到款信息主键
     * @return 到款信息
     */
    @Override
    public ConstractRecord selectConstractRecordById(Long id) {
        return constractRecordMapper.selectConstractRecordById(id);
    }

    /**
     * 查询到款信息列表
     *
     * @param constractRecord 到款信息
     * @return 到款信息
     */
    @Override
    public List<ConstractRecord> selectConstractRecordList(ConstractRecord constractRecord) {
        return constractRecordMapper.selectConstractRecordList(constractRecord);
    }

    /**
     * 新增到款信息
     *
     * @param constractRecord 到款信息
     * @return 结果
     */
    @Override
    public int insertConstractRecord(ConstractRecord constractRecord) {
        Contract contract = contractMapper.selectContractById(constractRecord.getConstractId());
        contract.setToMoney(DoubleUtil.sum(constractRecord.getMoney(), contract.getToMoney()));
        contractMapper.updateContract(contract);
        return constractRecordMapper.insertConstractRecord(constractRecord);
    }


    /**
     * 修改到款信息
     *
     * @param constractRecord 到款信息
     * @return 结果
     */
    @Override
    public int updateConstractRecord(ConstractRecord constractRecord) {
        ConstractRecord constractRecord1 = constractRecordMapper.selectConstractRecordById(constractRecord.getId());
        Double oldMoney = constractRecord1.getMoney();
        Contract contract = contractMapper.selectContractById(constractRecord1.getConstractId());
        contract.setToMoney(DoubleUtil.sum(contract.getToMoney(), DoubleUtil.cut(constractRecord.getMoney() ,oldMoney)));
        contractMapper.updateContract(contract);

        return constractRecordMapper.updateConstractRecord(constractRecord);
    }

    /**
     * 批量删除到款信息
     *
     * @param ids 需要删除的到款信息主键
     * @return 结果
     */
    @Override
    public int deleteConstractRecordByIds(String ids) {
        return constractRecordMapper.deleteConstractRecordByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除到款信息信息
     *
     * @param id 到款信息主键
     * @return 结果
     */
    @Override
    public int deleteConstractRecordById(Long id) {
        return constractRecordMapper.deleteConstractRecordById(id);
    }
}
